import pandas as pd
import requests


# 读取CSV文件
input_filename=input("请输入被处理的文件名（第一步生成，别忘.csv）：")
df = pd.read_csv(input_filename)
output_filename = input("请输入输出的文件名（加.csv）:")
# 定义起点坐标和API密钥
origin=input("请输入起点坐标（大厦坐标）：")
name=input("请输入起点名字(大厦名称)：")
key = input("请输入你的密钥：")
url_template = "https://restapi.amap.com/v5/direction/driving?origin={}&destination={}&key={}&destination_id=070500"

# 用于存储结果的列表
results = []

# 遍历DataFrame中的每一行
for index, row in df.iterrows():
    # 构造请求的URL
    destination = row['location']
    url = url_template.format(origin, destination, key)

    # 发送请求
    response = requests.get(url)

    # 解析响应内容
    res_data = response.json()

    # 检查API返回的状态码
    if res_data.get('status') == "1":  # 假设成功的状态码是"1"
        # 获取count和distance信息
        count = res_data['count']
        distance = res_data['route']['paths'][0]['distance']

        # 将结果添加到列表中
        results.append({
            'destination name': row['name'],
            'destination': row['location'],
            'count': count,
            'distance': distance,

        })
    else:
        print(f"Error for index {index}: {res_data.get('info')}")

url_template2 = "https://restapi.amap.com/v3/direction/driving?origin={}&destination={}&key={}&destination_id=070500"
# 用于存储duration的列表
durations = []
# 遍历DataFrame中的每一行
for index, row in df.iterrows():

        destination = row['location']
        url2 = url_template2.format(origin,destination, key)

        # 发送请求
        response2 = requests.get(url2)

        # 解析响应内容
        res_data2 = response2.json()

        # 检查API返回的状态码
        if res_data2.get('status') == "1" and 'route' in res_data and len(res_data['route']) > 0:
            # 获取duration信息
            duration = res_data2['route']['paths'][0]['duration'] # 假设duration在route的第一个元素中

            durations.append(duration)
        else:
            print(f"Error for index {index}: {res_data.get('info')}")
            durations.append(None)  # 如果出错，添加None或其他占位值



# 使用结果更新DataFrame
df_results = pd.DataFrame(results)


# 将新的列添加到原始DataFrame中
df_updated = pd.concat([df, df_results[['count', 'distance']]], axis=1)

# 将duration添加到原始DataFrame中

df_updated['duration'] = durations

new_data = {
    'origin': [name] * len(df),  #
    'origin of coordinate': [origin] * len(df)  # 为所有行添加坐标
}

# 创建一个新的DataFrame来存储新列
df_new_columns = pd.DataFrame(new_data)

# 将新DataFrame添加到原始DataFrame的最前方
df_updated2= pd.concat([df_new_columns, df_updated], axis=1)


# 保存更新后的DataFrame到新的CSV文件
df_updated2.to_csv(output_filename, index=False)